/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.service.impl;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import io.jboot.aop.annotation.Bean;
import io.jboot.components.rpc.annotation.RPCBean;
import io.jplus.JplusConsts;
import io.jplus.admin.model.Menu;
import io.jplus.admin.model.User;
import io.jplus.admin.service.MenuService;
import io.jplus.admin.service.UserService;
import io.jplus.core.plugin.shiro.ShiroService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Bean
@RPCBean
public class ShiroServiceImpl implements ShiroService {
    @Inject
    UserService userService;

    @Inject
    MenuService menuService;


    @Override
    public AuthorizationInfo buildAuthorizationInfo(PrincipalCollection principals) {

        Set<String> permList = new HashSet<>();
        List<Menu> menuList;
        String username = (String) principals.fromRealm("myRealm").iterator().next();
        User user = userService.findByUserName(username);
        if (JplusConsts.SUPER_ADMIN.equals(user.getId())) {
            menuList = menuService.findAll();
        } else {
            menuList = menuService.findListByUserId(user.getId());
        }

        for (Menu menu : menuList) {
            String perms = menu.getPerms();
            if (StrKit.notBlank(perms)) {
                permList.addAll(Arrays.asList(perms.trim().split(",")));
            }
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (permList.size() > 0) {
            authorizationInfo.addStringPermissions(permList);
        }
        return authorizationInfo;
    }

    @Override
    public Ret shiroLogin(String username, String password) {
        return userService.doLogin(username, password);
    }
}
